package com.niiwoo.civet.trade.service.local.refund;

import com.niiwoo.civet.base.enums.DeviceTypeEnum;
import com.niiwoo.civet.trade.constant.DatePatternConstant;
import com.niiwoo.civet.trade.dao.entity.CurrentDate;
import com.niiwoo.civet.trade.dao.mapper.CurrentDateMapperExt;
import com.niiwoo.civet.trade.dao.mapper.TradeConfigMapperExt;
import com.niiwoo.tripod.provider.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by bincun on 2018/1/3.
 *
 * 还款公共服务
 */
@Slf4j
@Service
public class CommonLocalService {
    @Autowired
    private CurrentDateMapperExt currentDateMapperExt;

    /**
     * 当前日切时间 key
     */
    private static String SETTINGSYSTEMDATETIME = "settingSystemDatetime";

    /**
     * 当前日切时间 key
     */
    private static final String KAOLALICAI_SETTING_DATETIME = "kaolalicaiSettingDatetime";
    private static final String FROM_DATE = "1970-01-01";


    public String day2String(Date date)
    {
        return FastDateFormat.getInstance(DatePatternConstant.YYYY_MM_DD).format(date);
    }

    /**
     * 取日切时间(当前日期-年月日)
     * @return
     */
    public Date getCurrentDate(){
       return this.getCurrentDate(SETTINGSYSTEMDATETIME);
    }

    public Date getKaolaCurrentDate(){
        return this.getCurrentDate(KAOLALICAI_SETTING_DATETIME);
    }

    public Date getCurrentDate(String key) {
        CurrentDate currentDate = currentDateMapperExt.selectByConfigKey(key);
        if (currentDate == null){
            log.error("日切时间不可空");
            throw new BizException("TRD_800007");
        }
        Date updateToday;
        try {
            String currentDateStr = FastDateFormat.getInstance(DatePatternConstant.YYYY_MM_DD).format(currentDate.getCurrentDate());
            if (FROM_DATE.equals(currentDateStr)) {
                //因表里面该字段不可为空，所以当设置的为1970-01-01则取当前时间
                updateToday = new DateTime(FastDateFormat.getInstance(DatePatternConstant.YYYY_MM_DD).format(new Date())).toDate();
            } else {
                updateToday = new DateTime(currentDateStr).toDate();
            }
        } catch (Exception e) {
            log.error("日切时间解析异常");
            throw new BizException("TRD_800007");
        }
        return updateToday;
    }

}
